# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 14:28:56 2019

@author: dell
"""

import talib
#import numpy as np
#import pandas as pd

def initialize(context):
    # 定义一个全局变量, 保存要操作的证券
    context.stocks = ['600036.XSHG']#,'601328.XSHG','600196.XSHG','600010.XSHG']
    # 设置我们要操作的股票池
    set_universe(context.stocks)
# 初始化此策略
def handle_data(context, data):
    # 取得当前的现金
    cash = context.portfolio.cash
    # 循环股票列表
    for stock in context.stocks:
        # 获取股票的数据
        h = attribute_history(stock, 25, '1d', ('high','low','close'))
        # 创建布林线买卖信号，包括价格和参数
        # 注意：函数使用的price必须是narray
        upper, middle, lower = talib.BBANDS(
                h['close'].values, 
                timeperiod=20,
                # number of non-biased standard deviations from the mean
                nbdevup=2,
                nbdevdn=2,
                # Moving average type: simple moving average here
                matype=0)
        # 获取当前股票的数据
        current_position = context.portfolio.positions[stock].amount
        # 获取当前股票价格
        current_price = data[stock].price
        # 当价格突破阻力线upper时，且拥有的股票数量>=0时，卖出所有股票
        if current_price >= upper[-1] and current_position >= 0:
            order_target(stock, 0)
        # 当价格跌破支撑线lower时, 且拥有的股票数量<=0时，则全仓买入
        elif current_price <= lower[-1]  and current_position <= 0:
            number_of_shares = int(cash/current_price)
            # 购买量大于0时，下单
            if number_of_shares > 0:
                # 买入股票
                order(stock, +number_of_shares)
                # 记录这次买入
                log.info("Buying %s" % (stock))
        record(upper=upper[-1],
           lower=lower[-1],
           mean=middle[-1],
           price=current_price,
           position_size=current_position) 
g.security = get_index_stocks('000300.XSHG') 
set_universe(g.security)
set_benchmark('000300.XSHG')
set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))

def handle_data(context, data):
     # 止损
    for stock in list(context.portfolio.positions.keys()):
        his = history(3, '1d', 'close', [stock])
        if ((1-(his[stock][-1]/his[stock][0]))>=0.05):
            order_target(stock, 0)
    
    # 调仓日交易
    for stock in g.security:
        if not data[stock].isnan():
            # 布林上下界
            mavg_price = data[stock].mavg(100)
            std_dev =data[stock].stddev(100, field='price')
            upper_band = mavg_price + 2 * std_dev
            lower_band = mavg_price - 2 * std_dev
            
            # 设定仓位
            num = len(context.portfolio.positions.keys())
            cash = context.portfolio.cash
            position = context.portfolio.positions[stock].amount
            if num>=10 and cash > 0:
                num_of_shares=cash/data[stock].price
            elif num<10 and cash > 0:
                cash2 = context.portfolio.cash/15
                num_of_shares=cash2/data[stock].price
            # 交易
            if data[stock].price < (0.95 * lower_band) and cash > 0 and position < 100:
                order(stock, +num_of_shares)
            elif data[stock].price > (1.05 * upper_band) and position > 0:
                order_target(stock, 0)
     